package mapred.util;

import java.util.Arrays;

import org.apache.hadoop.io.BytesWritable;

public class BytesReader {

	private byte[] data;

	private int pos;
	
	public BytesReader(byte[] data) {
		this.data = data;
		pos = 0;
	}

	public BytesReader(BytesWritable data) {
		this(Arrays.copyOfRange(data.getBytes(), 0, data.getLength()));
	}

	public boolean hasNext() {
		return this.hasNextBytes(1);
	}
	
	public byte next() {
		return this.nextBytes(1)[0];
	}
	
	public boolean hasNextInt() {
		return this.hasNextBytes(4);
	}
	
	public int nextInt() {
		return Bytes.Bytes2Integer(this.nextBytes(4));
	}
	
	public boolean hasNextLong() {
		return this.hasNextBytes(8);
	}
	
	public long nextLong() {
		return Bytes.Bytes2Long(this.nextBytes(8));
	}
	
	public boolean hasNextDouble() {
		return hasNextLong();
	}
	
	public double nextDouble() {
		return Bytes.Bytes2Double(this.nextBytes(8));
	}
	
	public int size() {
		return data.length;
	}

	public int remain() {
		return data.length - pos;
	}
	
	public void close() {
		data = null;
	}
	
	public boolean hasNextBytes(int i) {
		return (remain() >= i);
	}
	
	public byte[] nextBytes(int i) {
		byte[] ret = Arrays.copyOfRange(data, pos, pos + i);
		pos += i;
		return ret;
	}

	public void skip(int step) {
		pos = Math.min(pos + step, data.length);
	}
	
	public byte[] data() {
		return this.nextBytes(this.remain());
	}
}
